﻿using System.Web.Mvc;
using CVsharp.WebLib.Cache;

namespace CVsharp.MVClib.Log
{
    public class LogAttribute:ActionFilterAttribute
    {
        /// <summary>
        /// 日志内容
        /// </summary>
        public string LogContent { get; set; }
        private bool isOnline;
        /// <summary>
        /// 是否刷新记录到在线
        /// </summary>
        public bool IsOnline { get { return isOnline; } set { isOnline = value; } }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuted(ActionExecutedContext filterContext)  //OnActionExecuted会在动作（action）运行完成后执行
        {
            if (filterContext.Exception == null)    //如果出现异常，则不记录日常操作日志
            {
                #region 记录在线
                if (isOnline)
                {
                    var webh = new UsersOnline();
                    webh.CheckOnline();
                }
                #endregion
                var db = new Models.Entities.DBEntities();
                var log = new Models.Entities.CommonLog
                              {
                                  actionname = filterContext.ActionDescriptor.ActionName,
                                  controllername = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                                  logdate = System.DateTime.Now,
                                  logtype = LogContent,
                                  theuser = filterContext.HttpContext.User.Identity.Name == ""
                                          ? "null"
                                          : filterContext.HttpContext.User.Identity.Name
                              };
                db.AddToCommonLog(log);
                db.SaveChanges();
            }
        }
    }
}